/*
* ECARX Technology Limited is the owner of the copyright and the trade secret of this software. 
* Without permission, no one has the right to obtain, disclose or use this software in any way.
*/

package com.ecarx.camera.worker.sound;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;

import com.ecarx.camera.R;
import com.ecarx.camera.utils.LogUtils;
import com.jeremyliao.liveeventbus.utils.AppUtils;

import java.lang.ref.SoftReference;

public final class SoundPlayManger {
    private static final String TAG = "SoundPlayManger";

    private static final int VOLUME_RATIO_MULTIPLE = 100;
    private static final int ADJUST_VOLUME_MAX = 25;
    private static final int ADJUST_VOLUME_MIN = 2;
    private static final float ADJUST_VOLUME_STEP = 0.15f;

    private static final int SOUND_PRIORITY = 1;
    private static final int SOUND_LOOP = 0;
    private static final float SOUND_RATE = 1.0f;

    private static volatile SoundPlayManger instance = null;

    private SoftReference<SoundPool> soundPoolRef = null;
    private int mSoundId = -1;
    private boolean isLoadSoundIdComplete = false;

    private SoundPool.OnLoadCompleteListener mLoadCompleteListener = new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            LogUtils.d(TAG, "playSoundPool, onLoadComplete, status:" + status);
            isLoadSoundIdComplete = status == 0;
        }
    };

    private SoundPlayManger() {
    }

    //此处不可用类加载机制，应该用双重检查锁定，因为修改权限app被系统舜杀舜起时，需要释放并重新创建
    public static SoundPlayManger get() {
        if (instance == null) {
            synchronized (SoundPlayManger.class) {
                if (instance == null) {
                    instance = new SoundPlayManger();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化SoundPool
     */
    public void initSoundPool() {
        LogUtils.d(TAG, "initSoundPool");
        AudioAttributes attributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build();
        soundPoolRef = new SoftReference<>(new SoundPool.Builder().setMaxStreams(10)
                .setAudioAttributes(attributes).build());
        mSoundId = soundPoolRef.get().load(AppUtils.getApp(), R.raw.camera_capture, 1);
        soundPoolRef.get().setOnLoadCompleteListener(mLoadCompleteListener);
    }

    /**
     * 播放拍照声音
     */
    public synchronized void playShootSound() {
        if(soundPoolRef.get() == null){
            //兜底防止soundPool未初始化
            LogUtils.d(TAG, "soundPoolRef is null, initSoundPool again");
            initSoundPool();
        }
        LogUtils.d(TAG, "playShootSound loadSoundIdComplete:" + isLoadSoundIdComplete);
        AudioManager audioManager = (AudioManager) AppUtils.getApp().getSystemService(Context.AUDIO_SERVICE);
        float max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        boolean streamMute = audioManager.isStreamMute(AudioManager.STREAM_MUSIC);
        LogUtils.d(TAG, "playShootSound currentVolume:" + currentVolume);
        if (currentVolume <= 0 || streamMute) {
            LogUtils.d(TAG, "playShootSound mute.");
            return;
        }
        //max 实车39;
        float ratio = currentVolume / max;
        //放大倍数做对比
        int ratioTemp = (int) (ratio * VOLUME_RATIO_MULTIPLE);
        if (ratioTemp < ADJUST_VOLUME_MAX && ratioTemp > ADJUST_VOLUME_MIN) {
            //实车验证声音非常小,
            ratio += ADJUST_VOLUME_STEP;
        }
        if (soundPoolRef.get() != null && isLoadSoundIdComplete) {
            LogUtils.d(TAG, "playShootSound ratio:" + ratio);
            soundPoolRef.get().play(mSoundId, ratio, ratio, SOUND_PRIORITY, SOUND_LOOP, SOUND_RATE);
        }
    }

    /**
     * 释放资源
     */
    public void release() {
        LogUtils.d(TAG, "release, soundPool:" + soundPoolRef.get());
        if (soundPoolRef.get() != null) {
            soundPoolRef.get().release();
            soundPoolRef.clear();
        }
        instance = null;
    }
}

